<?php
// +----------------------------------------------------------------------
// | ThinkCMF [ WE CAN DO IT MORE SIMPLE ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2018 http://www.thinkcmf.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 小西瓜 <751707632@qq.com>
// | Author: 大西瓜 <321055156@qq.com>
// +----------------------------------------------------------------------
namespace app\fowl\controller;
use app\portal\model\UserLikeModel;
use cmf\controller\AdminBaseController;
use think\Db;
use app\admin\model\ThemeModel;
use app\portal\model\PortalPostModel;
use app\portal\model\CommentModel;
use app\portal\service\PostService;
use app\portal\model\PortalCategoryModel;

class AdminGambitController extends AdminBaseController
{
    /**
     * 话题列表
     * @adminMenu(
     *     'name'   => '学吧',
     *     'parent' => 'fowl/AdminMeeting/default',
     *     'remark' => '话题',
     * )
     */
    public function index()
    {
        $portalPost = new PortalPostModel();
        $param = $this->request->param();

        $categoryId = $this->request->param('category', 0, 'intval');
        $startTime = empty($param['start_time']) ? 0 : strtotime($param['start_time']);
        $endTime   = empty($param['end_time']) ? 0 : strtotime($param['end_time']);
        if (!empty($startTime) && !empty($endTime)) {
            $where['published_time'] = [['>= time', $startTime], ['<= time', $endTime]];
        } else {
            if (!empty($startTime)) {
                $where['published_time'] = ['>= time', $startTime];
            }
            if (!empty($endTime)) {
                $where['published_time'] = ['<= time', $endTime];
            }
        }
        if(!empty($categoryId)){
            $where['cate_id'] = $categoryId;
        }

        $keyword = empty($param['keyword']) ? '' : $param['keyword'];
        if (!empty($keyword)) {
            $where['post_title'] = ['like', "%$keyword%"];
        }

        $where['post_status'] = 1;//1已审核、0待审核
        //$where['delete_time'] = 0;//删除数据
        $categorys = Db::name('portal_category')->where('parent_id', 5)->field('id,name')->select();
        foreach($categorys as $cv){
            $cvdata[] = '<option value="'.$cv['id'].'">'.$cv['name'].'</option>';
        }
        $cvstr = implode(',', $cvdata);
        $result = $portalPost->where($where)->order('create_time DESC')->paginate(10);
        if(!empty($result)){
            foreach($result as $vs){
                $vs->categories;
                $vs->getuserinfo;
            }
        }
        $this->assign('articles', $result->items());
        $this->assign('page', $result->render());
        $this->assign('categorys', $cvstr);
        return $this->fetch();
    }

    /**
     * 话题置顶
     * @adminMenu(
     *     'name'   => '话题置顶',
     *     'parent' => 'index',
     *     'display'=> false,
     *     'hasView'=> false,
     *     'order'  => 10000,
     *     'icon'   => '',
     *     'remark' => '话题置顶',
     *     'param'  => ''
     * )
     */
    public function top()
    {
        $param           = $this->request->param();
        $portalPostModel = new PortalPostModel();
        if (isset($param['ids']) && isset($param["yes"])) {
            $ids = $this->request->param('ids/a');
            $portalPostModel->where(['id' => ['in', $ids]])->update(['is_top' => 1]);
            $this->traceLog('话题置顶', $param); // 操作日志
            $this->success("置顶成功！", '');
        }
        if (isset($_POST['ids']) && isset($param["no"])) {
            $ids = $this->request->param('ids/a');
            $portalPostModel->where(['id' => ['in', $ids]])->update(['is_top' => 0]);
            $this->traceLog('话题取消置顶', $param); // 操作日志
            $this->success("取消置顶成功！", '');
        }
    }

    /**
     * 话题推荐
     * @adminMenu(
     *     'name'   => '话题推荐',
     *     'parent' => 'index',
     *     'display'=> false,
     *     'hasView'=> false,
     *     'order'  => 10000,
     *     'icon'   => '',
     *     'remark' => '话题推荐',
     *     'param'  => ''
     * )
     */
    public function recommend()
    {
        $param           = $this->request->param();
        $portalPostModel = new PortalPostModel();

        if (isset($param['ids']) && isset($param["yes"])) {
            $ids = $this->request->param('ids/a');
            $portalPostModel->where(['id' => ['in', $ids]])->update(['recommended' => 1]);
            $this->traceLog('话题推荐', $param); // 操作日志
            $this->success("推荐成功！", '');
        }
        if (isset($param['ids']) && isset($param["no"])) {
            $ids = $this->request->param('ids/a');
            $portalPostModel->where(['id' => ['in', $ids]])->update(['recommended' => 0]);
            $this->traceLog('话题取消推荐', $param); // 操作日志
            $this->success("取消推荐成功！", '');
        }
    }

    /**
     * 话题删除
     * @adminMenu(
     *     'name'   => '话题删除',
     *     'parent' => 'index',
     *     'display'=> false,
     *     'hasView'=> false,
     *     'order'  => 10000,
     *     'icon'   => '',
     *     'remark' => '话题删除',
     *     'param'  => ''
     * )
     */
    public function deletetheme()
    {
        $id = $this->request->param('id', 0, 'intval');
        $updateinit = Db::name('portal_post');
        $find = $updateinit->where('id', $id)->find();
        if($find['delete_time'] == 0){
            $updateResult = $updateinit->where(['id' => $id])->update(['delete_time' => time()]);
            $this->traceLog('话题删除', $id); // 操作日志
        }else{
            $updateResult = $updateinit->where(['id' => $id])->update(['delete_time' => 0]);
            $this->traceLog('话题删除', $id); // 操作日志
        }
        if($updateResult){
            return $this->success("操作成功！", '');
        }
        return $this->success("操作成功！", '');
    }

    /**
     * 屏蔽话题
     */
    public function shieldtheme()
    {
        $id = $this->request->param('id', 0, 'intval');
        $updateinit = Db::name('portal_post');

        $find = $updateinit->where('id', $id)->find();
        if($find['post_status'] == 0){
            $updateResult = $updateinit->where(['id' => $id])->update(['post_status' => 1]);
            $this->traceLog('话题取消屏蔽', $id); // 操作日志
        }elseif($find['post_status'] == 1){
            $updateResult = $updateinit->where(['id' => $id])->update(['post_status' => 0]);
            $this->traceLog('话题屏蔽', $id); // 操作日志
        }else{
            $updateResult = false;
        }
        if($updateResult){
            return $this->success("操作成功！", '');
        }

        return $this->success("操作成功！", '');
    }

    /**
     * 编辑话题
     * @adminMenu(
     *     'name'   => '编辑话题',
     *     'parent' => 'index',
     *     'display'=> false,
     *     'hasView'=> true,
     *     'order'  => 10000,
     *     'icon'   => '',
     *     'remark' => '编辑话题',
     *     'param'  => ''
     * )
     */
    public function edit()
    {
        $id = $this->request->param('id', 0, 'intval');

        $portalPostModel = new PortalPostModel();
        $post            = $portalPostModel->where('id', $id)->find();
        $postCategories  = $post->categories()->alias('a')->column('a.name', 'a.id');
        $postCategoryIds = implode(',', array_keys($postCategories));

        $themeModel        = new ThemeModel();
        $articleThemeFiles = $themeModel->getActionThemeFiles('portal/Article/index');
        $this->assign('article_theme_files', $articleThemeFiles);
        $this->assign('post', $post);
        $this->assign('post_categories', $postCategories);
        $this->assign('post_category_ids', $postCategoryIds);

        return $this->fetch();
    }

    public function detail()
    {
        $id = $this->request->param('id', 0, 'intval');
        $commentInit = new CommentModel();
        $UserLikeModel_m = new UserLikeModel();
        $portalPost_m = new PortalPostModel();
        $queryResult = $portalPost_m->where('id', $id)->field('id,post_title,parent_id,post_status,post_content,post_like,user_id')->find();

        //$portalpostdata = $queryResult->toArray();
        $commentinfo = $queryResult->getcomments;//评论数据
        $queryResult['counts'] = count($queryResult->getcomments);//评论数量

        foreach($commentinfo as $cvalue){
            $cvalue['counts'] = $commentInit->getmanycommet(['parent_id' => $cvalue['id'], 'delete_time' => 0]);
            $cvalue['getlickcount'] = $UserLikeModel_m->getlikecount(['object_id' => $cvalue['id']]);

            $commentinfos[] = $cvalue;
        }
        unset($queryResult['getcomments']);
        isset($commentinfos) ? $queryResult['getcomments'] = $commentinfos : '';


        $getuserinfo = $queryResult->getuserinfo;//获取用户信息
        $getlickcount = $queryResult->getlickcount;//获取点赞数量
        $getfavoritecount = $queryResult->getfavoritecount;//获取收藏数量
        $queryResult['getlickcount'] = count($getlickcount);
        $queryResult['getfavoritecount'] = count($getfavoritecount);
        if(!empty($commentinfo)){
            foreach ($commentinfo as $cv){
                 if($cv['parent_id'] != 0){
                     $parent_idarray[] = $cv['parent_id'];
                 }
            }
        }
        $count = count($commentinfo);//评论数量
        if(isset($parent_idarray)){
            $uniqueDataArray = array_unique($parent_idarray);//parent_id唯一不重复的id;
            $wheremap['parent_id'] = ['in', $uniqueDataArray];
            $commentSonData = $commentInit->where($wheremap)->field('id,parent_id,status,delete_time,content,user_id,to_user_id,object_id,like_count')->select();

        }

        $commentSonData = isset($commentSonData) ? $commentSonData : '';
        $this->assign('count', $count);
        $this->assign('commentResult', $queryResult);
        $this->assign('commentsondata', $commentSonData);
        return $this->fetch();
    }

    /**
     * 屏蔽评论
     */
    public function commentshield()
    {
        $id = $this->request->param('id', 0, 'intval');
        $updateinit = Db::name('comment');

        $find = $updateinit->where('id', $id)->find();
        if($find['status'] == 0){
            $updateResult = $updateinit->where(['id' => $id])->update(['status' => 1]);
            $this->traceLog('取消屏蔽话题评论', $id); // 操作日志
        }elseif($find['status'] == 1){
            $updateResult = $updateinit->where(['id' => $id])->update(['status' => 0]);
            $this->traceLog('屏蔽话题评论', $id); // 操作日志
        }else{
            $updateResult = false;
        }
        if($updateResult){
            return $this->success("操作成功！", '');
        }
        return $this->error("操作失败！", '');
    }

    /**
     * 删除评论
     */
    public function commentdelete()
    {

        $id = $this->request->param('id', 0, 'intval');
        $updateinit = Db::name('comment');

        $find = $updateinit->where('id', $id)->find();
        if($find['delete_time'] == 0){
            $updateResult = $updateinit->where(['id' => $id])->update(['delete_time' => time()]);
            $this->traceLog('删除话题', $id); // 操作日志
        }else{
            $updateResult = $updateinit->where(['id' => $id])->update(['delete_time' => 0]);
            $this->traceLog('回收话题', $id); // 操作日志
        }

        if($updateResult){
            return $this->success("操作成功！", '');
        }
        return $this->error("操作失败！", '');
    }


    /**
     * 添加话题
     * @adminMenu(
     *     'name'   => '添加话题',
     *     'parent' => 'index',
     *     'display'=> false,
     *     'hasView'=> true,
     *     'order'  => 10000,
     *     'icon'   => '',
     *     'remark' => '添加话题',
     *     'param'  => ''
     * )
     */
    public function add()
    {
        $themeModel        = new ThemeModel();
        $articleThemeFiles = $themeModel->getActionThemeFiles('portal/Article/index');
        $this->assign('article_theme_files', 'fds');
        return $this->fetch();
    }



    /**
     * 话题分类选择对话框
     * @adminMenu(
     *     'name'   => '话题分类选择对话框',
     *     'parent' => 'index',
     *     'display'=> false,
     *     'hasView'=> true,
     *     'order'  => 10000,
     *     'icon'   => '',
     *     'remark' => '话题分类选择对话框',
     *     'param'  => ''
     * )
     */
    public function select()
    {
        $ids                 = $this->request->param('ids');
        $selectedIds         = explode(',', $ids);
        $portalCategoryModel = new PortalCategoryModel();

        $tpl = <<<tpl
<tr class='data-item-tr'>
    <td>
        <input type='checkbox' class='js-check' data-yid='js-check-y' data-xid='js-check-x' name='ids[]'
               value='\$id' data-name='\$name' \$checked>
    </td>
    <td>\$id</td>
    <td>\$spacer <a href='\$url' target='_blank'>\$name</a></td>
</tr>
tpl;

        $categoryTree = $portalCategoryModel->adminCategoryTableTree($selectedIds, $tpl);

        $where      = ['delete_time' => 0];
        $categories = $portalCategoryModel->where($where)->select();

        $this->assign('categories', $categories);
        $this->assign('selectedIds', $selectedIds);
        $this->assign('categories_tree', $categoryTree);
        return $this->fetch();
    }


    /**
     * 编辑话题分类提交
     * @adminMenu(
     *     'name'   => '编辑话题分类提交',
     *     'parent' => 'index',
     *     'display'=> false,
     *     'hasView'=> false,
     *     'order'  => 10000,
     *     'icon'   => '',
     *     'remark' => '编辑话题分类提交',
     *     'param'  => ''
     * )
     */
    public function editPost()
    {
        $data = $this->request->param();
        return json($data);
        $result = $this->validate($data, 'PortalCategory');

        if ($result !== true) {
            $this->error($result);
        }

        $portalCategoryModel = new PortalCategoryModel();

        $result = $portalCategoryModel->editCategory($data);

        if ($result === false) {
            $this->error('保存失败!');
        }

        $this->success('保存成功!');
    }

    public function publish()
    {
        $param           = $this->request->param();
        $portalPostModel = new PortalPostModel();
        if (isset($param['ids']) && isset($param["yes"])) {
            $ids = $this->request->param('ids/a');
            $portalPostModel->where(['id' => ['in', $ids]])->update(['post_status' => 1, 'published_time' => time()]);
            $this->traceLog('审核话题', $param); // 操作日志
            $this->success("审核成功！", '');
        }
        if (isset($param['ids']) && isset($param["no"])) {
            $ids = $this->request->param('ids/a');
            $portalPostModel->where(['id' => ['in', $ids]])->update(['post_status' => 0]);
            $this->traceLog('取消审核话题', $param); // 操作日志
            $this->success("取消审核成功！", '');
        }
    }
}
